package com.sky.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Resource
    private DishMapper dishMapper;

    @Resource
    private DishFlavorMapper dishFlavorMapper;

    @Resource
    private SetMealDishMapper setMealDishMapper;

    @Resource
    private CategoryMapper categoryMapper;
    @Resource
    private SetmealMapper setmealMapper;



    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.selectDishByCategoryId(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    /**
     * 添加菜品和菜品的味道
     * 这里同时修改多个数据表采用事务管理可以保证了事务一致性
     * @param dishDTO
     */
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.insert(dish);
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors!=null&& !flavors.isEmpty()){
            for (DishFlavor flavor : flavors) {
                //这里为了确保菜品的id回显，需要在字段上设置@TableId注解和在配置文件中
                //配置useGeneratedKeys=true&keyProperty=id
                flavor.setDishId(dish.getId());
                dishFlavorMapper.insert(flavor);
            }
        }
    }

    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        //动态增加Sql语句实现分页查询
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        //因为引入了mybatis分页插件所以查询的数据已经封装成page对象，page对象 extends ArrayList<E>
        //如果还想加入筛选条件，那么除了mybatis-plus，需要自己修改Sql语句（只支持单表操作）
        Page<DishVO> page = dishMapper.page(dishPageQueryDTO);
        PageResult pageResult = new PageResult(page.getTotal(), page.getResult());
        return pageResult;
    }

    @Override
    @Transactional
    public void deleteByIds(List<Long> ids) {
        //第一种情况：当删除的菜品的状态是启用时，不能删除
        for (Long id : ids) {
            Dish dish = dishMapper.selectById(id);
            //过关斩将，筛选删除失败的情况
            if (dish.getStatus()== StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //第二种情况：当删除的菜品有套餐id时，不能删除
        List<Long> setmealIds = setMealDishMapper.selectByDishId(ids);
        if (!setmealIds.isEmpty()){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //如果没有以上两种情况就可以正常删除菜品并删除对应的味道
        //这里直接调用mp的方法
        dishMapper.deleteBatchIds(ids);
        //这个是自己增加的方法
        dishFlavorMapper.deleteByDishId(ids);
    }

    /**
     * 查询dishid对应的数据封装为vo
     * @param id
     * @return
     */
    @Override
    @Transactional
    public DishVO getById(Long id) {
        Dish dish = dishMapper.selectById(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        String nameById = categoryMapper.getNameById(dish.getCategoryId());
        dishVO.setCategoryName(nameById);
        List<DishFlavor> byDishId = dishFlavorMapper.getByDishId(id);
        dishVO.setFlavors(byDishId);
        return dishVO;
    }

    /**
     * 修改菜品和对应的口味
     * @param dishDTO
     */
    @Transactional
    public void updateById(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //修改dish表
        dishMapper.updateDish(dish);
        //删除口味
        dishFlavorMapper.deleteById(dishDTO.getId());
        //新增口味
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors!=null&& !flavors.isEmpty()){
            for (DishFlavor flavor : flavors) {
                //这里为了确保菜品的id回显，需要在字段上设置@TableId注解和在配置文件中
                //配置useGeneratedKeys=true&keyProperty=id
                flavor.setDishId(dish.getId());
                dishFlavorMapper.insert(flavor);
            }
        }
    }

    /**
     * 根据分类id展示菜品
     * @param id
     * @return
     */
    @Override
    public List<Dish> list(Long id) {
        Dish dish = Dish.builder().categoryId(id)
                //只能添加上线的菜品
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.selectDishByCategoryId(dish);
    }


    /**
     * 菜品起售停售
     *
     * @param status
     * @param id
     */
    @Transactional
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.updateDish(dish);

        if (status == StatusConstant.DISABLE) {
            // 如果是停售操作，还需要将包含当前菜品的套餐也停售
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            // select setmeal_id from setmeal_dish where dish_id in (?,?,?)
            List<Long> setmealIds = setMealDishMapper.selectByDishId(dishIds);
            if (setmealIds != null && !setmealIds.isEmpty()) {
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealId)
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmealMapper.updateById(setmeal);
                }
            }
        }
    }
}
